package cn.medemede.servelt;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String site=filterConfig.getInitParameter("Site");
        System.out.println("网址名称："+site);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        String currentUrl=request.getRequestURI();
        String ctxPath=request.getContextPath();
        String targUrl=currentUrl.substring(ctxPath.length());

        HttpSession session=request.getSession(false);
        if (!("index.jsp".equals(targUrl))){
            System.out.println("1"+targUrl+"ctxPath:"+ctxPath+"currentURL:"+currentUrl);
            if (session==null||session.getAttribute("username")==null){
                String url_index = "index.jsp";
                response.sendRedirect(url_index);
            }else {
                filterChain.doFilter(request,response);
            }
        }else {
            filterChain.doFilter(request,response);
        }

    }

    @Override
    public void destroy() {

    }
}
